/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var ItbPartnerAreaModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`pa_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  //`partner_id` bigint(20) NOT NULL COMMENT '合伙人id',
  //`prov` bigint(20) DEFAULT NULL COMMENT '省id',
  //`city` bigint(20) DEFAULT NULL COMMENT '市id',
  //`dist` bigint(20) DEFAULT NULL COMMENT '区id',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0' COMMENT '删除flg',

};

ItbPartnerAreaModel.prototype = new ItbBaseModel();

// 取得表名
ItbPartnerAreaModel.prototype.getTableName = function(){
    return 'itb_partner_area';
};

// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbPartnerAreaModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'pa_id='+this.pa_id;
};



//------------------------------------------------------------------
/**
 * 获取高级合伙人管辖区域列表
 * @param userId
 * @param callback
 */
ItbPartnerAreaModel.prototype.getAreaListByUserId = function(userId, callback){

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' SELECT x.*, a1.name AS prov_name, a2.name AS city_name, a3.name AS dist_name '+
            ' FROM ( '+
            '   SELECT pa.pa_id, pa.partner_id, pa.prov, pa.city, pa.dist '+
            '   FROM itb_partner_area pa, itb_partner p, itb_user u '+
            '   WHERE u.del_flg=0 AND u.user_id= '+userId+
            '   AND p.del_flg=0 AND p.user_id=u.user_id '+
            '   AND pa.del_flg=0 AND pa.partner_id=p.partner_id ) x '+
            ' LEFT JOIN itb_area a1 ON a1.del_flg=0 AND a1.id = x.prov '+
            ' LEFT JOIN itb_area a2 ON a2.del_flg=0 AND a2.id = x.city '+
            ' LEFT JOIN itb_area a3 ON a3.del_flg=0 AND a3.id = x.dist '+
            ' ORDER BY x.pa_id ';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error){
                console.log(sql);
                return callback(error, null);
            }
            return callback(null, result);
        });
    });
};


//--------------------------------end-------------------------------

// 导出
module.exports = ItbPartnerAreaModel;